<template>
  <div class="points-content">
    <el-card class="points-card">
      <div class="points-header">
        <div class="points-total">
          <span>当前积分</span>
          <span class="points-count">{{ totalPoints }}</span>
        </div>
        <el-button 
          type="primary" 
          @click="handleSignToday" 
          :disabled="signedToday" 
          :loading="signLoading">
          {{ signedToday ? '今日已签到' : '立即签到' }}
        </el-button>
      </div>
      
      <el-calendar v-model="calendarDate" ref="calendarRef">
        <template #date-cell="{ data }">
          <div 
            class="calendar-cell" 
            :class="{ 
              'signed': signedDates.includes(data.day),
              'today': isToday(data.day),
              'disabled': isFutureDate(data.day)
            }"
            @click="handleCalendarSign(data.day)">
            <div class="calendar-day">{{ data.day.split('-').slice(2).join('-') }}</div>
            <el-icon v-if="signedDates.includes(data.day)" class="sign-icon">
              <Check />
            </el-icon>
          </div>
        </template>
      </el-calendar>
      
      <el-divider />
      
      <div class="points-rules">
        <h3>签到规则说明</h3>
        <el-timeline>
          <el-timeline-item
            v-for="(rule, index) in signRules"
            :key="index"
            :timestamp="rule.timestamp"
            placement="top"
          >
            <el-card>
              <h4>{{ rule.title }}</h4>
              <p>{{ rule.content }}</p>
            </el-card>
          </el-timeline-item>
        </el-timeline>
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, watch } from 'vue'
import { ElMessage, ElNotification } from 'element-plus'
import { Check } from '@element-plus/icons-vue'
import signApi from '@/api/sign'

const calendarDate = ref(new Date())
const signedDates = ref<string[]>([])
const totalPoints = ref(0)
const signLoading = ref(false)

// 签到相关数据
const continuousDays = ref(0)
const todayPoints = ref(0)
const rewardPoints = ref(0)

// 签到规则说明
const signRules = ref([
  {
    timestamp: '',
    title: '每日签到',
    content: '用户可以对当日进行签到，每次签到可获得1积分。'
  },
  {
    timestamp: '',
    title: '连续签到奖励',
    content: '连续签到第7天、第14天、第28天分别可获得额外奖励积分10分、20分、40分。'
  },
  {
    timestamp: '',
    title: '补签规则',
    content: '用户可以对当月以往的日期进行补签，每次补签可获得1积分，但补签不会获得连续签到奖励。'
  },
  {
    timestamp: '',
    title: '连续签到计算',
    content: '补签过后，下次签到时会算上补签天数。例如：今天只签到一天，但补签了过去5天，明天签到时就算连续签到7天，若达到奖励条件即可获得奖励积分。'
  }
])

// 获取当月签到记录
const fetchSignRecord = async () => {
  try {
    // 获取当前选中的年月
    const selectedYear = calendarDate.value.getFullYear()
    const selectedMonth = calendarDate.value.getMonth() + 1 // getMonth() 返回 0-11，需要加1
    
    // 获取当前实际的年月
    const currentYear = new Date().getFullYear()
    const currentMonth = new Date().getMonth() + 1
    
    // 如果是当前月份，则不传年月参数；否则传递年月参数
    let res: any
    if (selectedYear === currentYear && selectedMonth === currentMonth) {
      res = await signApi.getRecord()
    } else {
      res = await signApi.getRecord(selectedYear, selectedMonth)
    }
    
    const records = res.data.data
    const year = calendarDate.value.getFullYear()
    const month = calendarDate.value.getMonth()
    
    signedDates.value = []
    
    // 解析签到记录
    for (let day = 1; day <= 31; day++) {
      const date = new Date(year, month, day)
      // 确保日期在当前月份内
      if (date.getMonth() !== month) continue
      
      const dateStr = date.toISOString().split('T')[0]
      // 根据数组中的0/1来判断是否签到，索引从0开始，所以day需要减1
      if (Array.isArray(records) && records[day - 1] === 1) {
        signedDates.value.push(dateStr)
      }
    }
  } catch (error) {
    console.error('获取签到记录失败:', error)
  }
}

// 获取用户总积分
const fetchTotalPoints = async () => {
  try {
    const res: any = await signApi.getPoints()
    totalPoints.value = res.data.data || 0
  } catch (error) {
    console.error('获取总积分失败:', error)
  }
}

// 签到操作
const handleSign = async (date: string) => {
  if (signLoading.value) return
  
  // 如果是未来日期，不能签到
  if (isFutureDate(date)) {
    ElMessage.warning('不能签到未来日期')
    return
  }
  
  // 检查是否是当月日期
  const currentDate = new Date()
  const currentYear = currentDate.getFullYear()
  const currentMonth = currentDate.getMonth()
  
  const selectedDate = new Date(date)
  const selectedYear = selectedDate.getFullYear()
  const selectedMonth = selectedDate.getMonth()
  
  // 如果不是当月日期，不能补签
  if (selectedYear !== currentYear || selectedMonth !== currentMonth) {
    ElMessage.warning('只能补签当月的日期')
    return
  }
  
  // 如果已经签到，不再重复签到（除了今天可以显示签到结果）
  if (signedDates.value.includes(date) && date !== getCurrentDate()) {
    ElMessage.info('该日期已签到')
    return
  }
  
  signLoading.value = true
  try {
    // 判断是今日签到还是补签
    if (date === getCurrentDate()) {
      // 今日签到
      const res: any = await signApi.signIn()
      const { signDays, signPoints, rewardPoints: reward } = res.data
      
      // 更新签到状态
      if (!signedDates.value.includes(date)) {
        signedDates.value = [...signedDates.value, date]
      }
      
      // 更新统计数据
      continuousDays.value = signDays || 0
      todayPoints.value = signPoints || 0
      rewardPoints.value = reward || 0
      
      // 获取最新总积分
      await fetchTotalPoints()
      
      ElNotification({
        title: '签到成功',
        message: `连续签到${signDays}天，获得${signPoints}积分${reward > 0 ? `，奖励${reward}积分` : ''}`,
        type: 'success',
        duration: 3000
      })
    } else {
      // 补签
      const res: any = await signApi.signRepair(date)
      const signPoints = res.data.data
      
      // 更新签到状态
      if (!signedDates.value.includes(date)) {
        signedDates.value = [...signedDates.value, date]
      }
      
      // 获取最新总积分
      await fetchTotalPoints()
      
      ElNotification({
        title: '补签成功',
        message: `补签获得${signPoints}积分`,
        type: 'success',
        duration: 3000
      })
    }
  } catch (error: any) {
    console.log(error.message)
  } finally {
    signLoading.value = false
  }
}

// 今日签到
const handleSignToday = () => {
  const today = getCurrentDate()
  handleSign(today)
}

// 日历点击签到
const handleCalendarSign = (date: string) => {
  handleSign(date)
}

// 获取当前日期字符串
const getCurrentDate = () => {
  return new Date().toISOString().split('T')[0]
}

// 判断是否为今天
const isToday = (date: string) => {
  return date === getCurrentDate()
}

// 判断是否为未来日期
const isFutureDate = (date: string) => {
  return date > getCurrentDate()
}

// 计算今天是否已签到
const signedToday = computed(() => {
  const today = getCurrentDate()
  return signedDates.value.includes(today)
})

// 监听日历日期变化，重新获取签到记录
watch(calendarDate, () => {
  fetchSignRecord()
})

// 组件挂载时初始化数据
onMounted(() => {
  fetchSignRecord()
  fetchTotalPoints()
})
</script>

<style scoped>
.points-content {
  max-width: 1200px;
  margin: 0 auto;
}

.points-card {
  border: none;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.points-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 30px;
  padding-bottom: 20px;
  border-bottom: 1px solid #f0f0f0;
}

.points-total {
  display: flex;
  flex-direction: column;
}

.points-total span:first-child {
  font-size: 14px;
  color: #666;
  margin-bottom: 5px;
}

.points-count {
  font-size: 32px;
  font-weight: bold;
  color: #409eff;
}

.calendar-cell {
  height: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  position: relative;
  border-radius: 4px;
  transition: all 0.2s;
}

.calendar-cell:hover:not(.disabled) {
  background-color: #ecf5ff;
  color: #409eff;
}

.calendar-cell.signed {
  background-color: #e8f4ff;
  color: #409eff;
}

.calendar-cell.today {
  background-color: #409eff;
  color: white;
}

.calendar-cell.today:hover {
  background-color: #409eff;
}

.calendar-cell.today.signed {
  background-color: #409eff;
}

.calendar-cell.disabled {
  cursor: not-allowed;
  color: #c0c4cc;
  background-color: transparent;
}

.calendar-cell.disabled:hover {
  background-color: transparent;
}

.calendar-day {
  font-size: 12px;
  margin-bottom: 2px;
}

.sign-icon {
  position: absolute;
  bottom: 2px;
  font-size: 10px;
}

.points-stats {
  margin-top: 20px;
}

.stat-item {
  text-align: center;
  padding: 20px 0;
}

.stat-value {
  font-size: 24px;
  font-weight: bold;
  color: #333;
  margin-bottom: 5px;
}

.stat-label {
  font-size: 14px;
  color: #666;
}

:deep(.el-calendar__body) {
  padding: 10px;
}

:deep(.el-calendar-table .el-calendar-day) {
  height: 40px;
}

@media (max-width: 768px) {
  .points-header {
    flex-direction: column;
    gap: 15px;
    text-align: center;
  }
  
  .points-stats {
    margin-top: 10px;
  }
  
  .stat-item {
    padding: 10px 0;
  }
  
  .stat-value {
    font-size: 20px;
  }
}
</style>